<template>
  <el-dialog
          :model-value="dialogVisible"
          title="内容包媒资列表"
          :before-close="handleCancelDialog"
          width="80%"
          top="5vh"
  >
    <el-row>
      <el-col :span="18">
        <el-select
                placeholder="请选择媒资类型"
                v-model="selectedMediatype"
                clearable
                class="input-w mr10"
                @change="handleSelectMediatype"
                size="mini">
          <el-option
                  v-for="type in mediaTypeList"
                  :key="type.mediatype"
                  :label="type.name"
                  :value="type.mediatype"
          />
        </el-select>
        <el-autocomplete
                placeholder="请输入媒资名称"
                v-model.trim="queryList.keyword"
                size="mini"
                clearable
                class="input-w mr10"
                value-key="name"
                :fetch-suggestions="handleMediaSearchSuggest"
                :trigger-on-focus="false"
                :highlight-first-item="true"
                @select="handleFilterMedia"
                @clear="handleFilterMedia"
        />
        <el-button type="primary" size="mini" @click="handleFilterMedia">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </el-button>
      </el-col>
      <el-col :span="6">
        <div align="right">
          <el-button type="primary" size="mini" @click="handleConfirmAddMedia">
            <el-icon>
              <check />
            </el-icon>
            确定添加
          </el-button>
        </div>
      </el-col>
      <el-col :span="24" class="mt10">
        <el-table
          ref="packageMediaRef"
          :data="tableData.listData"
          v-loading="isloading"
          border
          style="width: 100%"
          max-height="400"
          @row-click="handleRowClick"
          @select="handleSelect"
          @select-all="handleSelectAll"
        >
          <el-table-column type="selection" width="50" :selectable="handleSelectable"/>
          <el-table-column label="缩略图" width="80">
            <template #default="{row, $index}">
              <span @click.stop>
                <el-image
                        v-if="row.covers && row.covers.length > 0"
                        :src="row.covers[0].isself == 1 ? row.covers[0].viewurl + '&width=60px' : row.covers[0].viewurl"
                        :initial-index="$index"
                        :preview-src-list="imgSrcList"
                />
              </span>
            </template>
          </el-table-column>
          <el-table-column label="媒资ID" width="80px" align="center" prop="mediaid"></el-table-column>
          <el-table-column label="媒资名称" show-overflow-tooltip>
            <template #default="{row}">
              <span class="txttdellipsis">
                <span v-if="row.highlight && row.highlight.name" v-html="row.highlight.name"></span>
                <span v-else>{{row.name}}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="媒资类型" prop="mediatypename"></el-table-column>
          <el-table-column label="媒资分类" prop="catname"></el-table-column>
          <el-table-column label="来源企业">
            <template #default="{row}">
              <span v-if="currentCorpid != row.corpid && corpPartnerObj[row.corpid] != undefined">{{corpPartnerObj[row.corpid]}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" :sortable="true" width="180px">
            <el-table-column label="修改时间" :sortable="true">
              <template #default="{row}">
                <div>{{row.ctime ? row.ctime.replace('T', ' ') : '--'}}</div>
                <div>{{row.mtime ? row.mtime.replace('T', ' ') : '--'}}</div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="状态" :sortable="true" prop="inuse">
            <template #default="{row}">
              <el-tag type="success" size="mini" v-if="row.inuse == 1">上线</el-tag>
              <el-tag type="danger" size="mini" v-else>下线</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="添加状态">
            <template #default="{row}">
              <span v-if="row.columnids && row.columnids.includes(columnid)" style="color: red">已添加</span>
              <span v-else>未添加</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24" class="mt10">
        <table-pagination
          :query-list="queryList"
          :total="tableData.total"
          @pagination="getPackageMediaList"
        />
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
  import {reactive, ref, nextTick} from 'vue'
  import {useStore} from 'vuex'
  import {getSearchMediaList, mediaSearchSuggest} from "../../../../api/package/project";
  import {columnRelMedia} from "@/api/package/package";
  import {Search, Check} from '@element-plus/icons'
  import {getCorpPartner} from "@/api/corppartner";
  import TablePagination from "@/views//public/TablePagination";
  import {ElMessage} from 'element-plus'

  export default {
    name: "ProjectPackageMedia",
    components: {Search, Check, TablePagination},
    props: {
      packageid: {
        type: String,
        required: true
      },
      columnid: {
        type: Number,
        required: true
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      mediaTypeList: {
        type: Array,
        required: true
      }
    },
    emits: ['handleCancelDialog', 'reloadColumnMedias'],
    setup(props, context) {
      const store = useStore()
      const currentCorpid = store.getters.corpinfo.corpid
      const queryList = reactive({
        page: 1,
        pagesize: 25,
        ifext: 1,
        packageid: undefined,
        keyword: undefined,
        mediatypes: [],
      })
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const isloading = ref(false)
      const corpPartnerObj = reactive({})
      const imgSrcList = ref([])
      const selectedMediatype = ref(undefined)
      const formData = reactive({
        columnid: undefined,
        ifext: 1,
        packageid: undefined,
        mediaids: []
      })
      const packageMediaRef = ref(null)

      /** 获取内容包媒资 **/
      const getPackageMediaList = () => {
        queryList.packageid = props.packageid
        isloading.value = true
        getSearchMediaList(queryList).then(response => {
          isloading.value = false
          if (response.errcode == 0) {
            const {total, lists} = response.data
            tableData.listData = lists
            tableData.total = total
            imgSrcList.value = []
            nextTick(() => {
              tableData.listData.forEach(row => {
                if (row.covers && row.covers.length > 0) {
                  imgSrcList.value.push(row.covers[0].viewurl)
                } else {
                  imgSrcList.value.push('')
                }
              })
            })
          }
        })
      }
      /** 关闭弹框 **/
      const handleCancelDialog = () => {
        context.emit('handleCancelDialog')
      }
      /** 搜索建议 **/
      const handleMediaSearchSuggest = async (queryString, resolve) => {
        const query = {
          ifext: 1,
          packageid: props.packageid,
          prefix: queryString
        }
        const suggestionData = ref([])
        await mediaSearchSuggest(query).then(response => {
          if (response.errcode == 0) {
            suggestionData.value = response.data.lists
          }
        })
        resolve(suggestionData.value)
      }
      /** 获取合作企业列表 **/
      const getCorpPartnerList = () => {
        getCorpPartner({partnertype: 0, corpid: currentCorpid}).then(response => {
          if (response.errcode == 0) {
            response.data.list.forEach(function (v) {
              corpPartnerObj[v.corpid] = v.corpname
            })
          }
        })
      }
      /** 搜索媒资 **/
      const handleFilterMedia = () => {
        queryList.page = 1
        getPackageMediaList()
      }
      /** 切换媒资类型 **/
      const handleSelectMediatype = () => {
        if (selectedMediatype.value) {
          queryList.mediatypes = [selectedMediatype.value]
        } else {
          queryList.mediatypes = []
        }
        queryList.page = 1
        getPackageMediaList()
      }
      /** 判断媒资是否可选 **/
      const handleSelectable = (row) => {
        return !row.columnids.includes(props.columnid)
      }
      /** 点击行选择媒资 **/
      const handleRowClick = (row) => {
        if (!row.columnids.includes(props.columnid)) {
          handleSelectedMediaIds(row)
          if (formData.mediaids.includes(row.mediaid)) {
            packageMediaRef.value.toggleRowSelection(row, true)
          } else {
            packageMediaRef.value.toggleRowSelection(row, false)
          }
        }
      }
      /** 单选媒资 **/
      const handleSelect = (selection, row) => {
        handleSelectedMediaIds(row)
      }
      /** 全选媒资 **/
      const handleSelectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (!formData.mediaids.includes(row.mediaid)) {
              formData.mediaids.push(row.mediaid)
            }
          })
        } else {
          formData.mediaids = []
        }
      }
      /** 获取媒资选择的媒资ID **/
      const handleSelectedMediaIds = (row) => {
        if (formData.mediaids.includes(row.mediaid)) {
          const index = formData.mediaids.findIndex(d => d == row.mediaid)
          formData.mediaids.splice(index, 1)
        } else {
          formData.mediaids.push(row.mediaid)
        }
      }
      /** 确认添加媒资 **/
      const handleConfirmAddMedia = () => {
        if (formData.mediaids.length <= 0) {
          ElMessage({type: 'warning', message: '请先选择要添加的媒资', duration: 2000})
        } else {
          formData.columnid = props.columnid
          formData.packageid = parseInt(props.packageid)
          columnRelMedia(formData).then(response => {
            if (response.errcode == 0) {
              formData.mediaids = []
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              handleCancelDialog()
              context.emit('reloadColumnMedias')
            }
          })
        }
      }

      const init = () => {
        queryList.page = 1
        getCorpPartnerList()
        getPackageMediaList()
      }

      return {
        init,
        handleCancelDialog,
        queryList,
        tableData,
        handleMediaSearchSuggest,
        corpPartnerObj,
        handleFilterMedia,
        isloading,
        currentCorpid,
        imgSrcList,
        getPackageMediaList,
        handleSelectMediatype,
        selectedMediatype,
        handleSelectable,
        handleRowClick,
        handleSelect,
        handleSelectAll,
        packageMediaRef,
        handleConfirmAddMedia
      }
    }
  }
</script>

<style>
  em{
    color: red;
    font-style: normal;
  }
</style>
<style scoped>

</style>
